import { ref, type Ref } from "vue";
import { defineStore, storeToRefs } from "pinia";
import type { Component } from "@visual/types";
import { useComponent, useContextMenu } from "@visual/stores";
import { nanoid } from "nanoid";

import { PxMessage } from "px-ui";
type CopyComType = {
  data: Component | undefined | null;
  index: number | null;
};
export const useCopy = defineStore("copyStore", () => {
  const componentStore = useComponent();
  const menuStroe = useContextMenu();
  const { menuTop, menuLeft } = storeToRefs(menuStroe);
  const { addComponent, deleteComponent } = componentStore;
  const { curComponent, curComponentIndex } = storeToRefs(componentStore);
  const copyData: Ref<CopyComType | undefined | null> = ref();
  const isCut: Ref<Boolean> = ref(false);

  function copy() {
    if (!curComponent.value) {
      PxMessage({
        message: "请选择组件",
        type: "warning"
      });
      return;
    }
    setCopData();
    isCut.value = false;
  }
  function paste(isMouse) {
    if (!copyData.value) {
      PxMessage({
        message: "请选择组件",
        type: "warning"
      });
      return;
    }
    const data = copyData.value.data;

    if (isMouse) {
      data.style.top = menuTop.value;
      data.style.left = menuLeft.value;
    } else {
      data.style.top += 10;
      data.style.left += 10;
    }

    addComponent({ component: deepCopyHelper(data) });
  }
  function cut() {
    if (!curComponent.value) {
      PxMessage({
        message: "请选择组件",
        type: "warning"
      });
      return;
    }
    restorePreCutData();
    setCopData();
    isCut.value = true;
    deleteComponent(curComponentIndex.value);
  }
  function restorePreCutData() {
    if (isCut.value && copyData.value) {
      const data = deepCopy(copyData.value.data);
      const index = copyData.value.index;
      addComponent({ component: data, index });

      if (curComponentIndex.value >= index) {
        // 如果当前组件索引大于等于插入索引，需要加一，因为当前组件往后移了一位
        curComponentIndex.value = curComponentIndex.value + 1;
      }
    }
  }
  function setCopData() {
    copyData.value = {
      data: deepCopy(curComponent.value),
      index: curComponentIndex.value
    };
  }
  return {
    copy,
    paste,
    cut
  };
});

function deepCopy(data) {
  return JSON.parse(JSON.stringify(data));
}

function deepCopyHelper(data) {
  const result = deepCopy(data);
  result.id = nanoid();
  if (result.component === "Group") {
    result.propValue.forEach((component, i) => {
      result.propValue[i] = deepCopyHelper(component);
    });
  }

  return result;
}
